/*
    Copyright (C) 2013 maik.jablonski@jease.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sample.web.person;

import jfix.db4o.Database;
import jfix.zk.Checkbox;
import jfix.zk.Datefield;
import jfix.zk.ObjectEditor;
import jfix.zk.Passwordfield;
import jfix.zk.Textfield;
import sample.domain.Person;

public class Editor extends ObjectEditor<Person> {

	Textfield firstname = new Textfield();
	Textfield lastname = new Textfield();
	Datefield birthday = new Datefield();
	Textfield login = new Textfield();
	Passwordfield password = new Passwordfield();
	Passwordfield passwordRepeat = new Passwordfield();	
	Checkbox administrator = new Checkbox();
	
	public void init() {
		add("Firstname", firstname, "Please enter the firstname of the person.");
		add("Lastname", lastname, "Please enter the lastname of the person.");
		add("Birthday", birthday, "Please enter the birthday of the person.");
		add("Login", login, "Please enter a login name for the person");
		add("Password", password, "Please enter a password for the person.");
		add("Password (Repeat)", passwordRepeat, "Please repeat the password.");
		add("Administrator", administrator, "Please check if person is administrator.");
	}

	public void load() {
		firstname.setText(getObject().getFirstname());
		lastname.setText(getObject().getLastname());
		birthday.setDate(getObject().getBirthday());
		login.setText(getObject().getLogin());
		password.setText(getObject().getPassword());
		passwordRepeat.setText(getObject().getPassword());
		administrator.setChecked(getObject().isAdministrator());
	}

	public void save() {
		getObject().setFirstname(firstname.getText());
		getObject().setLastname(lastname.getText());
		getObject().setBirthday(birthday.getDate());
		getObject().setLogin(login.getText());
		getObject().setPassword(password.getText());
		getObject().setAdministrator(administrator.isChecked());
		Database.save(getObject());
	}

	public void delete() {
		Database.delete(getObject());
	}

	public void validate() {
		validate(login.isEmpty(), "Login is required");
		validate(password.isEmpty()
				|| !password.getText().equals(passwordRepeat.getText()),
				"Passwords do not match");
		validate(firstname.isEmpty(), "Firstname required");
		validate(lastname.isEmpty(), "Lastname required");
	}

}
